package com.zwy.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zwy.common.exception.BusinessException;
import com.zwy.common.exception.ResultCode;
import com.zwy.core.domain.entity.TbUser;
import com.zwy.core.domain.entity.TbUserRole;
import com.zwy.core.mapper.TbUserMapper;
import com.zwy.core.mapper.TbUserRoleMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final TbUserMapper userMapper;
    private final TbUserRoleMapper userRoleMapper;

    public UserDetailsServiceImpl(TbUserMapper userMapper,TbUserRoleMapper userRoleMapper){
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        TbUser user = userMapper.selectOne(new LambdaQueryWrapper<TbUser>()
                .eq(TbUser::getUsername, username));
        if(ObjectUtil.isEmpty(user)){
            throw new BusinessException(ResultCode.USER_NOT_EXIST);
        }
        //查询用户角色
        List<TbUserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<TbUserRole>()
                .eq(TbUserRole::getUserId, user.getId()));

        //构建权限集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (TbUserRole userRole : userRoles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+userRole.getRoleId()));
        }

        //返回SpringSecurity用户对象
        return new User(
                user.getUsername(),
                user.getPassword(),
                true,
                true,
                true,
                true,
                authorities
        );
    }
}
